from django.core.exceptions import ObjectDoesNotExist
from django.http import JsonResponse
# Create your views here.
from django.views import View

from project_manage.libs.storage.forms import OneImageUploadForm
from project_manage.libs.storage.models import ImageStorage


# @method_decorator(login_required, name='dispatch')
class UploadFileByOne(View):
    response_data = {
        'data': None,
        'msg': '',
        'code': 0,
    }

    def post(self, request):
        form = OneImageUploadForm(request.POST, request.FILES)
        if not form.is_valid():
            self.response_data['msg'] = 1
            error_msg_list = []
            for items in form.errors.values():
                error_msg_list.append(items[0])
            error_msg_str = ''.join(error_msg_list)
            self.response_data['msg'] = error_msg_str
            return JsonResponse(self.response_data)

        result = form.save()
        self.response_data['code'] = 1
        self.response_data['data'] = {'pk': result.pk, 'url': result.file_obj.url}
        return JsonResponse(self.response_data)

    def delete(self, request):
        pk = request.GET.get('pk')
        if pk:
            try:
                image = ImageStorage.objects.get(pk=pk)
                image.delete()
            except ObjectDoesNotExist as e:
                self.response_data['msg'] = '不存在PK'
                return JsonResponse(self.response_data)
            except Exception as e:
                self.response_data['msg'] = '发生未知错误'
                return JsonResponse(self.response_data)
            self.response_data['code'] = 1
            self.response_data['msg'] = '删除成功'
            return JsonResponse(self.response_data)
        else:
            self.response_data['msg'] = '参数错误'
            return JsonResponse(self.response_data)
